using System;
using System.Collections;
using DataServices;

namespace DataLayer
{
	/// <summary>
	/// Summary description for Query.
	/// </summary>
	
	public class Query
	{
		private string queryString;
		private object[] parameters;
		private string tableName;
		private Type objectType;
		private ArrayList parametersString = new ArrayList();
		
		public Query(Type objectType, string queryString, object[] parameters, string tableName)
		{
			this.objectType = objectType;
			this.queryString = queryString;
			this.parameters = parameters;
			this.tableName = tableName;
		}
		
		public string QueryString
		{
			get { return queryString; }
			set { queryString = value; }
		}

		public object[] Parameters
		{
			get { return parameters; }
			set { parameters = value; }
		}

		public Type ObjectType
		{
			get { return objectType; }
			set { objectType = value; }
		}

		public string TableName
		{
			get { return tableName; }
			set { tableName = value; }
		}

		public bool Parse()
		{
			int parameterNumber = 0;
			
			string[] words = queryString.Split(' ');
			
			foreach (string wd in words)
			{
				if (wd.StartsWith("@"))
				{
					parametersString.Add(wd);
					parameterNumber++;
				} else
				{
					// For parameteres like: '%@var%'
					string newWd = wd.Trim(new char[] {'\'', '%', '(', ')'});
					if (newWd.StartsWith("@"))
					{
						parametersString.Add(newWd);
						parameterNumber++;
					}
				}
			}
			
			return (parameterNumber == parameters.Length);
		}
		
		
		public Command Execute(DataSource ds)
		{
			if (Parse())
			{
				Command command = new Command(QueryString,ds.Connection,ds);
			
				int idx = 0;
				foreach (string parameterName  in parametersString)
				{
					command.AddParameter(parameterName, parameters[idx++]);
				}
			
				return command;
			} else
				throw new ApplicationException("Query structure is incorrect.");
			
		}
	}
}
